package com.xgkj.diyiketang.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.easemob.EMCallBack;
import com.easemob.EMError;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.easeui.domain.EaseUser;
import com.easemob.exceptions.EaseMobException;
import com.easyvaas.sdk.core.EVSdk;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.xgkj.diyiketang.EatShowApp;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.hxsdk.DemoHelper;
import com.xgkj.diyiketang.hxsdk.PreferenceManager;
import com.xgkj.diyiketang.security.MD5;
import com.xgkj.diyiketang.task.IsHaveOpenIDTask;
import com.xgkj.diyiketang.task.LoginTask;
import com.xgkj.diyiketang.task.ThirdLoginTask;
import com.xgkj.diyiketang.util.AppMetaData;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.JpushUtil;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.wxapi.WXEntryActivity;
import com.xgkj.diyiketang.yizhibo.Constants;

import java.lang.ref.WeakReference;
import java.util.LinkedHashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by Administrater on 2015/12/10.
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private Context mContext;
    private static final String TAG = "LoginActivity";
    private static final String PHONE_REGEX = "1[34578]\\d{9}";
    private static final int PHONE_LENGTH = 11;
    private EditText phoneEdit;
    private EditText pswEdit;
    private Button mLoginButton;
    private String mPhone;
    private String mPsw;
    private TextView forgetPswText;
    private TextView registerText;
    private TextView qqloginText;
    private TextView weixinloginText;
    private int loginId = -1;
    private int qqTaskID = -1;
    private int weixinTaskID = -1;
    private int openTaskID = -1;
    private int isHaveOPenTaskID = -1;
    private String localPsw;
    private String currentUsername;
    private String currentPassword = "123456";
    IWXAPI wxApi = null;
    public static String mAppid;
    //private final String QQ_APP_ID = "1105281988";//"1104548348";
    //private final String QQ_APP_ID = "1105084520";
    public static Tencent mTencent;
    public static String openidString;
    private static String thirdIconUrl;
    public Bitmap bitmap = null;
    public static String nicknameString;
    private WeiXinReceiver wxReceiver;
    private int thirdType = 2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        mContext = this;
        initView();
        wxApi = WXAPIFactory.createWXAPI(getApplicationContext(), null);
        wxApi.registerApp(ProtocolConst.APP_ID);
    }

    private void initView() {
        phoneEdit = (EditText) findViewById(R.id.login_phone);
        pswEdit = (EditText) findViewById(R.id.login_psw);
        pswEdit.setTransformationMethod(PasswordTransformationMethod
                .getInstance());
        mLoginButton = (Button) findViewById(R.id.login_btn);
        forgetPswText = (TextView) findViewById(R.id.login_forgetpsw);
        registerText = (TextView) findViewById(R.id.login_register);
        qqloginText = (TextView) findViewById(R.id.login_qq);
        weixinloginText = (TextView) findViewById(R.id.login_weixin);
        mLoginButton.setOnClickListener(this);
        forgetPswText.setOnClickListener(this);
        registerText.setOnClickListener(this);
        qqloginText.setOnClickListener(this);
        weixinloginText.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_btn:
                if (checkInput()) {
                    loginTask();
                    //doHXlogin();
                }
                break;
            case R.id.login_forgetpsw:
                Intent forget_intent = new Intent(mContext, ForgetPswActivity.class);
                startActivity(forget_intent);
                break;
            case R.id.login_register:
                Intent register_intent = new Intent(mContext, RegistActivity.class);
                startActivity(register_intent);
                break;
            case R.id.login_qq:
                thirdType = 1;
                onClickLogin();
                break;
            case R.id.login_weixin:
                thirdType = 0;
                sendWxAuthRequest();
                break;
            default:
                break;
        }
    }

    class WeiXinReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(WXEntryActivity.WEIXIN_LOGIN_SUCCESS_ACTION)) {
                if (wxReceiver != null) {
                    unregisterReceiver(wxReceiver);
                    wxReceiver = null;
                }
                openidString = intent.getStringExtra(ProtocolConst.WEIXIN_OPENID);
                thirdIconUrl = intent.getStringExtra("LOGOURL");
                nicknameString = intent.getStringExtra("NICK");
                if (nicknameString != null) {
                    EatShowApp.getACache().put(Constants.WEIXIN_NICKNAME, nicknameString);
                }
                isHaveOpenId();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (wxReceiver != null) {
            unregisterReceiver(wxReceiver);
            wxReceiver = null;

        }
    }

    /**
     * 微信登录
     */
    private void sendWxAuthRequest() {

        if (wxApi.isWXAppInstalled()) {
            if (wxReceiver == null) {
                wxReceiver = new WeiXinReceiver();
                IntentFilter filter = new IntentFilter();
                filter.addAction(WXEntryActivity.WEIXIN_LOGIN_SUCCESS_ACTION);
                registerReceiver(wxReceiver, filter);

            }
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "wechat_sdk_demo";
            //拉起微信授权，授权结果在WXEntryActivity中接收处理
            wxApi.sendReq(req);
        } else {
            Toast.makeText(this, "微信未安装", Toast.LENGTH_SHORT).show();
        }
    }
//    private void doHXlogin(){
//        currentUsername = phoneEdit.getText().toString().trim();
//        currentPassword = pswEdit.getText().toString().trim();
//        PalLog.e("用户名",currentUsername);
//        PalLog.e("密码",currentPassword);
//        EMChatManager.getInstance().login(currentUsername,currentPassword,new EMCallBack() {//回调
//            @Override
//            public void onSuccess() {
//                runOnUiThread(new Runnable() {
//                    public void run() {
//                        EMGroupManager.getInstance().loadAllGroups();
//                        EMChatManager.getInstance().loadAllConversations();
//                        PalLog.e("main", "登陆聊天服务器成功！");
//                    }
//                });
//                // 进入主页面
//                startActivity(new Intent(LoginActivity.this,MainActivity.class));
//                finish();
//            }
//
//            @Override
//            public void onProgress(int progress, String status) {
//
//            }
//
//            @Override
//            public void onError(int code, String message) {
//                PalLog.e("main", "登陆聊天服务器失败！");
//            }
//        });
//    }

    private void loginTask() {
//        LoginTask loginTask = new LoginTask(mPhone, mPsw);
//        loginTask.addListener(new LoginTaskEventListener(mContext));
//        loginId = getEatShowApp().getTaskManager().addTask(loginTask);
//        PalLog.e(TAG, "loginId:" + loginId);
//        String channel = AppMetaData.getMetaValue(mContext, "UMENG_CHANNEL");
//
//        PalLog.e("渠道",channel);
//        String areaname = EatShowSetting.getInstance(mContext).getFirstLocal();
        LoginTask loginTask = new LoginTask(mPhone, mPsw);
        loginTask.addListener(new LoginTaskEventListener(mContext));
        loginId = getEatShowApp().getTaskManager().addTask(loginTask);
//        PalLog.e(TAG, "loginId:" + loginId);
    }

    class LoginTaskEventListener extends ShowToastTaskEventListener {
        public LoginTaskEventListener(Context context) {
            super(context);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);

            if (taskId == loginId) {
                EatShowSetting.getInstance(mContext).setLoginName(mPhone);
                EatShowSetting.getInstance(mContext).setLoginPsw(mPsw);
                EatShowSetting.getInstance(mContext).setThirdNickname(null);
                EatShowSetting.getInstance(mContext).setThirdLogo(null);
                EatShowSetting.getInstance(mContext).setThirdOpenid(null);
                EatShowSetting.getInstance(mContext).setThirdType(-1);
                if (data != null) {
                    final EatShowUserInfo userInfo = (EatShowUserInfo) data;
                    getEatShowApp().setmUserInfo(userInfo);
                    currentUsername = userInfo.getUserId();
                    EatShowApp.getACache().put(Constants.USER_ID, userInfo.getUserId());
//                    boolean isbusiness = userInfo.isBusiness();
//                    EatShowSetting.getInstance(mContext).setIsBusiness(isbusiness);
                    openidString = currentUsername;
//                    PalLog.e("id", currentUsername);
                    if (userInfo.getTagList() != null && userInfo.getTagList().size() > 0) {
                        Set<String> tagList = new LinkedHashSet<String>(userInfo.getTagList());
                        JPushInterface.setAliasAndTags(getApplicationContext(), currentUsername, tagList, mAliasCallback);
                    } else {
                        JPushInterface.setAlias(getApplicationContext(), currentUsername, mAliasCallback);
                    }
                    EMChatManager.getInstance().login(currentUsername, currentPassword, new EMCallBack() {//回调
                        @Override
                        public void onSuccess() {
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    EaseUser user = new EaseUser(currentUsername);
                                    user.setNick(userInfo.getNickName());
                                    user.setAvatar(userInfo.getUserLogo());
                                    DemoHelper.getInstance().saveContact(user);
                                    PreferenceManager.getInstance().setCurrentUserAvatar(userInfo.getUserLogo());
                                    PreferenceManager.getInstance().setCurrentUserNick(userInfo.getNickName());
                                    EMGroupManager.getInstance().loadAllGroups();
                                    EMChatManager.getInstance().loadAllConversations();

                                    if (!TextUtils.isEmpty(userInfo.getUserId())) {
                                        String userId = userInfo.getUserId();
//                                        initSdk(userId);
                                        EatShowSetting.getInstance(mContext).setUserId(userInfo.getUserId());

                                        Intent it = new Intent(mContext, MainActivity.class);
                                        startActivity(it);
                                        finish();
                                    }
//                                    PalLog.e("main", "登陆聊天服务器成功！");
                                }
                            });
//                            // 进入主页面
//                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
//                            finish();
                        }

                        @Override
                        public void onProgress(int progress, String status) {

                        }

                        @Override
                        public void onError(int code, String message) {
//                            PalLog.e("正常登录失败", "登陆聊天服务器失败！");
                            doHXRegist();
                        }
                    });
                }

            } else if (taskId == openTaskID) {
                Toast.makeText(mContext, R.string.login_success, Toast.LENGTH_SHORT)
                        .show();

                EatShowUserInfo esinfo = (EatShowUserInfo) data;
                getEatShowApp().setmUserInfo(esinfo);
                String chanelSchool = esinfo.getChanelSchoolName();
//                if(!TextUtils.isEmpty(chanelSchool)){
//                    getEatShowApp().getmUserInfo().setSchoolName(chanelSchool);
//                }
                EatShowSetting.getInstance(mContext).setThirdNickname(esinfo.getNickName());
                EatShowSetting.getInstance(mContext).setThirdOpenid(openidString);
                EatShowSetting.getInstance(mContext).setThirdLogo(esinfo.getUserLogo());
                EatShowSetting.getInstance(mContext).setThirdType(thirdType);
                EatShowSetting.getInstance(mContext).setLoginName(null);
                EatShowSetting.getInstance(mContext).setLoginPsw(null);
                if (esinfo.getTagList() != null && esinfo.getTagList().size() > 0) {
                    Set<String> tagList = new LinkedHashSet<String>(esinfo.getTagList());
                    JPushInterface.setAliasAndTags(getApplicationContext(), esinfo.getUserId(), tagList, mAliasCallback);
                } else {
                    JPushInterface.setAlias(getApplicationContext(), esinfo.getUserId(), mAliasCallback);
                }
                PreferenceManager.getInstance().setCurrentUserAvatar(esinfo.getUserLogo());
                PreferenceManager.getInstance().setCurrentUserNick(esinfo.getNickName());

                String schoolName = esinfo.getSchoolName();
                if (TextUtils.isEmpty(schoolName)) {
                    Intent wintent = new Intent(mContext, WanshanziliaoActivity.class);
                    wintent.putExtra("school", chanelSchool);
                    startActivity(wintent);
                    finish();
                } else {
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }


            } else if (taskId == isHaveOPenTaskID) {
                if (data != null) {
                    JSONObject json = (JSONObject) data;
                    boolean isHave = json.getBoolean("isHaveOpenId");
                    if (isHave) {
                        doHXLogin();
                    } else {
                        doHXRegist();
                    }
//                    ThirdLoginTask open = new ThirdLoginTask(openidString,
//                            nicknameString, thirdIconUrl);
//                    open.addListener(new LoginTaskEventListener(mContext));
//                    openTaskID = getEatShowApp().getTaskManager().addTask(open);
//                    String areaname = EatShowSetting.getInstance(mContext).getFirstLocal();
                    String channel = AppMetaData.getMetaValue(mContext, "UMENG_CHANNEL");
                    ThirdLoginTask open = new ThirdLoginTask(openidString,
                            nicknameString, thirdIconUrl, channel, thirdType);
                    open.addListener(new LoginTaskEventListener(mContext));
                    openTaskID = getEatShowApp().getTaskManager().addTask(open);
                }
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            getEatShowApp().setmUserInfo(null);
        }
    }

    //初始化直播sdk
    private void initSdk(String userId) {
        String appID;
        if (TextUtils.isEmpty(Constants.appID)) {
            return;
        } else {
            appID = Constants.appID;
        }

        String accessKey;
        if (TextUtils.isEmpty(Constants.accessKey)) {
            return;
        } else {
            accessKey = Constants.accessKey;
        }

        String secretKey;
        if (TextUtils.isEmpty(Constants.secretKey)) {
            return;
        } else {
            secretKey = Constants.secretKey;
        }

        String userID;
        if (TextUtils.isEmpty(EatShowApp.getACache().getAsString(Constants.USER_ID))) {
            return;
        } else {
            userID = EatShowApp.getACache().getAsString(Constants.USER_ID);
        }

        EVSdk.setInitListener(new EVSdk.OnSDKInitListener() {
            @Override
            public void onSuccess() {
            }

            @Override
            public void onFailed(int code, String msg) {
            }
        });
        EVSdk.init(getApplicationContext(), appID, accessKey, secretKey, userId);
    }

    private void doHXLogin() {
        EMChatManager.getInstance().login(openidString, currentPassword, new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    public void run() {
                        EMGroupManager.getInstance().loadAllGroups();
                        EMChatManager.getInstance().loadAllConversations();
//                        PalLog.e("main", "登陆聊天服务器成功！。。。。。。。。。。。。。");
                    }
                });
//                            // 进入主页面
//                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
//                            finish();
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
//                PalLog.e("main", "登陆聊天服务器失败！");
            }
        });
    }

    private void doHXRegist() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    // 调用sdk注册方法
                    PalLog.e("进入环信注册流程", openidString);
                    EMChatManager.getInstance().createAccountOnServer(openidString, "123456");
                    runOnUiThread(new Runnable() {
                        public void run() {
//                            PreferenceManager.getInstance().setCurrentUserAvatar(thirdIconUrl);
//                            PreferenceManager.getInstance().setCurrentUserNick(nicknameString);
                            doHXLogin();
//                            if (!LoginActivity.this.isFinishing())
//                                //Toast.makeText(getApplicationContext(), getResources().getString(R.string.Registered_successfully), Toast.LENGTH_SHORT).show();
//                            finish();
                        }
                    });
                } catch (final EaseMobException e) {
                    runOnUiThread(new Runnable() {
                        public void run() {

                            int errorCode = e.getErrorCode();
                            if (errorCode == EMError.NONETWORK_ERROR) {
                                // Toast.makeText(getApplicationContext(), getResources().getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
                            } else if (errorCode == EMError.USER_ALREADY_EXISTS) {
                                // Toast.makeText(getApplicationContext(), getResources().getString(R.string.User_already_exists), Toast.LENGTH_SHORT).show();
                            } else if (errorCode == EMError.UNAUTHORIZED) {
                                //Toast.makeText(getApplicationContext(), getResources().getString(R.string.registration_failed_without_permission), Toast.LENGTH_SHORT).show();
                            } else if (errorCode == EMError.ILLEGAL_USER_NAME) {
                                //Toast.makeText(getApplicationContext(), getResources().getString(R.string.illegal_user_name),Toast.LENGTH_SHORT).show();
                            } else {
                                //Toast.makeText(getApplicationContext(), getResources().getString(R.string.Registration_failed) + e.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            }
        }).start();
    }


    private boolean checkInput() {
        mPhone = phoneEdit.getText().toString();
        mPsw = MD5.digest(pswEdit.getText().toString());
        if (TextUtils.isEmpty(mPhone) || mPhone.length() != PHONE_LENGTH
                || !mPhone.matches(PHONE_REGEX)) {
            Toast.makeText(mContext, R.string.no_phone, Toast.LENGTH_SHORT)
                    .show();
            return false;
        } else if (TextUtils.isEmpty(mPsw)) {
            Toast.makeText(mContext, R.string.no_psw, Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        return true;
    }

    public void isHaveOpenId() {
        IsHaveOpenIDTask isTask = new IsHaveOpenIDTask(openidString);
        isTask.addListener(new LoginTaskEventListener(mContext));
        isHaveOPenTaskID = getEatShowApp().getTaskManager().addTask(isTask);
    }


    // ----------------------------------------QQ登录-------------------------------------------------------
    private void onClickLogin() {
        mAppid = ProtocolConst.QQ_ID;
        mTencent = Tencent.createInstance(mAppid, getApplicationContext());
        mTencent.login(LoginActivity.this, "all", new BaseUiListener());
    }

    private class BaseUiListener implements IUiListener {

        @Override
        public void onCancel() {
//            PalLog.e(TAG, "onCancel......");
        }

        @Override
        public void onComplete(Object response) {
            //  Intent intent = new Intent(LoginActivity.this, MainActivity.class);

            try {
                // 获得的数据是JSON格式的，获得你想获得的内容
                // 如果你不知道你能获得什么，看一下下面的LOG
//                PalLog.e(TAG, "-------------" + response.toString());
                openidString = (JSONObject.parseObject(response.toString()))
                        .getString("openid");
                // intent.putExtra("openId", openidString);
                // openidTextView.setText(openidString);
//                PalLog.e(TAG, "-------------" + openidString);
                // access_token= ((JSONObject)
                // response).getString("access_token"); //expires_in =
                // ((JSONObject) response).getString("expires_in");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            /**
             * 到此已经获得OpneID以及其他你想获得的内容了
             * QQ登录成功了，我们还想获取一些QQ的基本信息，比如昵称，头像什么的，这个时候怎么办？
             * sdk给我们提供了一个类UserInfo，这个类中封装了QQ用户的一些信息，我么可以通过这个类拿到这些信息
             * 如何得到这个UserInfo类呢？
             */
            QQToken qqToken = mTencent.getQQToken();
            UserInfo info = new UserInfo(getApplicationContext(), qqToken);
            // 这样我们就拿到这个类了，之后的操作就跟上面的一样了，同样是解析JSON
            info.getUserInfo(new IUiListener() {

                public void onComplete(final Object response) {
//                    PalLog.e(TAG, "---------------111111");
                    Message msg = new Message();
                    msg.obj = response;
                    msg.what = 0;
                    getMyHandler().sendMessage(msg);
                    // nicknameString = response.toString();
//                    PalLog.e(TAG, "-----111---" + response.toString());
                    /**
                     * 由于图片需要下载所以这里使用了线程，如果是想获得其他文字信息直接 在mHandler里进行操作
                     *
                     */

                    /*new Thread() {

                        @Override
                        public void run() {

                            JSONObject json = JSONObject.parseObject(response
                                    .toString());
                            PalLog.e(TAG, "返回：" + json);
                            thirdIconUrl = (JSONObject.parseObject(response
                                    .toString())).getString("figureurl_qq_2");
                            PalLog.e(TAG, "-------------1111111111" + thirdIconUrl);
                            try {
                                getEatShowApp().getmUserInfo().setUserLogo(
                                        json.getString("figureurl_qq_2"));
                                getEatShowApp().getmUserInfo().setNickName(
                                        json.getString("nickname"));
                                bitmap = QQLoginUtil.getbitmap(json
                                        .getString("figureurl_qq_2"));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            Message msg = new Message();
                            msg.obj = bitmap;
                            msg.what = 1;
                            getMyHandler().sendMessage(msg);
                        }
                    }.start();*/
                }

                public void onCancel() {
//                    PalLog.e(TAG, "--------------111112");
                }

                public void onError(UiError arg0) {
//                    PalLog.e(TAG, "-111113" + ":" + arg0);
                }

            });
            //  startActivity(intent);
        }

        @Override
        public void onError(UiError arg0) {
//            PalLog.e(TAG, "onError......");
        }

    }

    private Handler myHandler;

    private Handler getMyHandler() {

        if (myHandler == null) {
            myHandler = new LoginHandler(this);
        }
        return myHandler;
    }

    static class LoginHandler extends Handler {
        private WeakReference<LoginActivity> mActivity;

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                JSONObject response = JSONObject
                        .parseObject(msg.obj.toString());
                if (response.containsKey("nickname")) {
                    try {
                        nicknameString = response.getString("nickname");
                        thirdIconUrl = (JSONObject.parseObject(response
                                .toString())).getString("figureurl_qq_2");
//                        PalLog.e(TAG, "--" + nicknameString);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    mActivity.get().isHaveOpenId();
                }
            } else if (msg.what == 1) {
//                Bitmap bitmap = (Bitmap) msg.obj;
            }
        }

        public LoginHandler(LoginActivity activity) {
            mActivity = new WeakReference<LoginActivity>(activity);
        }
    }


    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, final String alias, final Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
//                    PalLog.e(TAG, logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
//                    PalLog.e(TAG, logs);
                    if (JpushUtil.isConnected(getApplicationContext())) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                JPushInterface.setAliasAndTags(getApplicationContext(), alias, tags, mAliasCallback);
                            }
                        }, 60 * 1000);
                    } else {
//                        PalLog.e(TAG, "No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
//                    PalLog.e(TAG, logs);
            }
        }
    };


//    protected Handler mHandler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//
//
//        }
//
//    };
}
